package com.fang.config.service;

import com.fang.config.event.ApplicationContext;
import com.fang.config.event.MsgEvent;
import com.fang.config.event.OrderProductEvent;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.Clock;

/**
 * @author Fang Ruichuan
 * @date 2022-09-13 15:51
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderService {

    // 注入ApplicationContext用来发布事件
    private final ApplicationContext applicationContext;

    /**
     * 下单
     * @author Fang Ruichuan
     * @date 2022/9/13 15:53
     * @param orderId orderId
     * @return String
     */
    @SneakyThrows
    public String buyOrder(String orderId) {
        long start = Clock.systemUTC().millis();
        // 1.查询订单详情

        // 2.检验订单价格（同步处理）
        applicationContext.publishEvent(new OrderProductEvent(this, orderId));
        // 3.短信通知（异步处理）
        applicationContext.publishEvent(new MsgEvent(orderId));
        long end = Clock.systemUTC().millis();
        log.info("任务全部完成，总耗时：({})毫秒", (end - start));
        return "购买成功";
    }

}
